const config = require("../utils/config");
const encrypt = require("../utils/encrypt");
const loginService = require("../services/loginService");
const JWT = require("../utils/JWT");
const appSetting = require("../utils/appSetting");
const https = require("https");
module.exports = {
       /**
        * 小程序 验证是否已经登录过,登录过就避免重复登录
        * @param {*} req 
        * @param {*} res 
        * @param {*} next 
        */
       verifyBindUser: async (req, res, next) => {
              const { code } = req.body;
              const appid = appSetting.AppID;
              const secret = appSetting.AppSecret;
              https.get(
                     `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`,
                     (resp) => {
                            let data = "";
                            resp.on("data", (chunk) => {
                                   data += chunk;
                            });

                            resp.on("end", async() => {
                                   const wx = JSON.parse(data);
                                    let response=await loginService.getUserByOpenID(wx.openid);
                                   if (response == null) {
                                          //没有绑定
                                          res.json({
                                                 code: 0,
                                                 isBind: false,
                                                 message: "no bind",
                                                 openid: wx.openid,
                                          });
                                   }else{
                                          let uuid = config.UUID();
                                          const result = await loginService.setToken(uuid, response.UAccount);
                                          if (result?.affectedRows > 0) {
                                                 //加密token
                                                 const token = JWT.jwtSign({ tokens: uuid });
                                                 res.json({
                                                        code: 0,
                                                        isBind: true,
                                                        token: token
                                                 })
                                          } else {
                                                 //存入失败，报错
                                                 result = {
                                                        code: -1,
                                                        message: "登陆失败,请联系管理员"
                                                 }
                                          }
                                   }
                            })
                     }
              )
       },
       /**
        * 点击绑定按钮 短信验证账号与验证码登录
        * @param {*} req 
        * @param {*} res 
        * @param {*} next 
        */
       smsLoginverify: async (req, res, next) => {
              const { phone, verifySms, openid } = req.body;
              console.log(openid);
              //验证是否为受邀用户
              const result = await loginService.verifyIsInvitedUser(phone);
              if (result == null) {
                     res.json({
                            code: -1,
                            message: "您还不是受邀用户,请受邀后重试"
                     });
                     return
              }
              //验证短信是否有效,是否为最新验证码,根据登录状态修改openid
              const result2 = await loginService.smsLoginverify(phone, verifySms, openid);
              if (result2.code === 0) {
                     let uuid = config.UUID();
                     //设置token
                     const result3 = await loginService.setToken(uuid, phone);
                     //存入成功
                     if (result3?.affectedRows > 0) {
                            //加密token
                            const token = JWT.jwtSign({ tokens: uuid });
                            result2.token = token;
                            res.json(result2)
                     } else {
                            //存入失败，报错
                            result = {
                                   code: -1,
                                   message: "登陆失败,请联系管理员"
                            }
                     }
              } else {
                     res.json(result2)
              }

       },
       /**
        * 验证是否为受邀请用户 是的话下发验证码
        */
       verifyIsInvitedUser: async (req, res, next) => {
              const { phone } = req.body;
              const result = await loginService.verifyIsInvitedUser(phone);
              if (result == null) {
                     res.json({
                            code: -1,
                            message: "您还不是受邀用户,请受邀后重试"
                     });
                     return
              }

              const verifySms = parseInt(Math.random() * 8999) + 1000;
              //确认为受邀用户,下发验证码
              const result2 = await loginService.addPhoneVerifySms(phone, verifySms);
              if (result2) {
                     res.json({
                            code: 0,
                            message: "ok",
                            data: verifySms,
                     });
              } else {
                     res.json({
                            code: -500,
                            message: "获取失败,请联系客服处理"
                     });
              }




       },












       //验证用户身份后,获取当前登录对象
       getCurrUser: (req, res, next) => {
              return res.json({ code: 0, data: res.user });
       },

       //拦截路径
       filterPath: async (req, res, next) => {
              //放行接口
              const result = appSetting.releaseUrl.find(d => d == req.url);
              if (result != undefined) {
                     next();
                     return
              }
              //从请求中获取令牌
              let code = req.headers.authorization;
              code = code.split(" ")[1];
              if (code == "" || code.length == 0) {
                     res.status(401).send("excption01");
                     return
              }

              //解密令牌
              const uToken = await JWT.jwtVerify(code);

              if (uToken == null) {
                     res.status(401).send("excption02");
                     return
              }

              //根据令牌查找对象
              let user = await loginService.getCurrUser(uToken);
              if (user == null) {
                     res.status(401).send("excption03");
                     return
              }

              if (user.length == 0) {
                     res.status(401).send("excption03");
                     return
              }
              res.user = user;
              next();

       },
       //登录账号
       logins: async (req, res, next) => {
              const { account, password } = req.body;  //获取账号密码
              // const timesa=new Date();
              // console.log(Date.parse(timesa));
              //密码加密成32位字符串
              const newPwd = encrypt.Md5Encrypt(password);
              //查询结果
              let result = await loginService.login(account, newPwd);
              //查询成功 code=0
              if (result.code == 0) {
                     //生成token
                     const tokens = config.UUID();
                     //将token存入数据库
                     const result2 = await loginService.setToken(tokens, account);
                     //存入成功
                     if (result2?.affectedRows > 0) {
                            const token = JWT.jwtSign({ tokens: tokens });
                            result.token = token
                     } else {
                            //存入失败，报错
                            result = {
                                   code: -1,
                                   message: "登陆失败,请联系管理员"
                            }
                     }
              }
              res.json(result);

       }
}